package com.shiro.realm;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * 配合 Demo3 使用，通过查询数据库来获取用户信息
 *
 *
 * 注意：
 * @author hjwStart
 * @time 2022-11-21 11:19
 * @version: 1.0
 */
@Slf4j
public class MyRealm extends AuthorizingRealm {
    // 获取授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    public String getName() {
        // 父类的方法全路径 + "_" + 数字，烦人，重写一下就要全路径
        return this.getClass().getName();
    }

    // 获取认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("进入{}#doGetAuthenticationInfo方法",this.getName());
        log.info("开始连接数据库");
        log.info("获取数据库连接");
        log.info("获取Subject的Principals(username)");
        String principals = authenticationToken.getPrincipal().toString();
        log.info("执行SQL");
        log.info("解析结果集");
        String credentials = "123123"; // 从数据库中查询出来的密码
        SimpleAuthenticationInfo authenticationInfo = null;
//        if ("admin".equals(principals) || "hjw".equals(principals)){
        if (true){
            authenticationInfo = new SimpleAuthenticationInfo(principals,credentials,this.getName());
        }else {
            log.error("用户不存在");
        }
        return authenticationInfo;
    }
}
